package com.foronenet.mud;

import java.io.IOException;
import java.net.*;
import java.util.Date;

public class MudUdpClientDemo {
    public static void main(String[] args)  {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(6699);
            byte[] bytes = new byte[12];
            String ip = "127.0.0.1";
//        String ip = "192.168.0.3";
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(ip), 8080);

            while (true) {
                String[] hexArray = RandomPrivateData.get();
                for (String hex : hexArray){
                    packet.setData(hexStringToBytes(hex));
                    socket.send(packet);
                    System.out.println(System.currentTimeMillis() + ": " + hex);
                    Thread.sleep(500);
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

    }

    /**
     * 将16进制形式的字符串，转换为字节数组
     *
     * @param hex 没有空格的16进制字符串
     */
    public static byte[] hexStringToBytes(String hex) {
        int len = hex.length();
        byte[] b = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            b[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
        }
        return b;
    }
}
